package ua.kharkov.knure.mikhaylov.st4.web.command;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.mikhaylov.st4.db.entities.Account;
import ua.kharkov.knure.mikhaylov.st4.db.entities.Card;
import ua.kharkov.knure.mikhaylov.st4.db.entities.User;
import ua.kharkov.knure.mikhaylov.st4.db.management.DBManager;
import ua.kharkov.knure.mikhaylov.st4.settings.LocaleData;
import ua.kharkov.knure.mikhaylov.st4.settings.Path;

/**
 * Command - writes account into session and redirects to an account viewing
 * page
 * 
 * @author Saint
 * 
 */
public class ViewAccountCommand extends Command {

	private static final long serialVersionUID = 2191152559048019958L;
	private static final Logger log = Logger
			.getLogger(ViewAccountCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {

		log.debug("Command starts");

		HttpSession session = request.getSession();

		User user = (User) session.getAttribute("user");
		log.trace("Found user in session --> " + user);
		Account account = null;

		// Those strange if blocks are appropriate to the ways to get into this
		// command -
		// from accounts page (via id) or from account page (via account). It's
		// a bad logic
		// but there's no time to make it better
		if (request.getParameter("id") != null) {

			long id = Long.valueOf(request.getParameter("id"));
			log.trace("Got id from session --> " + id);
			account = (Account) DBManager.getInstance().findAccountById(id,
					user);

			session.setAttribute("account", account);
		}

		if (account == null) {
			if (session.getAttribute("account") == null) {
				String errorMessage = LocaleData.getResourceBundle().getString(
						"servlet.error.account.null");
				request.setAttribute("errorMessage", errorMessage);
				log.error("errorMessage --> " + errorMessage);
				return Path.PAGE_ERROR;
			} else {
				account = (Account) session.getAttribute("account");
			}
		}
		log.debug("User account wrote to session --> " + account);

		List<Card> cards = DBManager.getInstance().findCardsByAccount(account);
		session.setAttribute("cards", cards);

		log.debug("Account cards wrote to session --> " + cards.size()
				+ " items");

		log.debug("Command finished");
		return Path.PAGE_ACCOUNT;
	}
}
